<template>

  <div class="tree" @scroll="rollingLoad">        
        <div class="tree-wrapper" v-loading="loading">        
            <el-tree
                class="el-tree"
                :data="departmentData"        
                node-key="id"
                ref="department"
                highlight-current    
                lazy     
                :props="departmentDefaultProps"        
                :default-expanded-keys="defaultExpanded"       
                @node-click="departmentNodeClick"       
                @node-expand="departmentNodeExpand"        
             
                empty-text="暂无数据~">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>
                        <i :class="data.icons" class="iconfont"></i>
                        <span
                            class="peopel-title"
                            :class="{ 'checked-color' : data.isChecked }">
                            {{ data.name }}
                        </span>
                        <span
                            class="peopel-dept-name"
                            :class="{ 'checked-color' : data.isChecked }">
                            ({{ data.user_count }})
                        </span>
                    </span>
                </span>
            </el-tree>
        </div>
    </div>

</template>

<script>


export default {
  data() {
    
    return {
      loading:false,
      scrollLoadingFlag:false,
      departmentData:[],
      defaultExpanded:[],
      departmentDefaultProps: {
          children: 'children',
          label: 'label'
      }


    };
  },

  methods: {

    scrollLoad(event) {
        let target = event.target;
        const offsetHeight = target.offsetHeight;
        const scrollTop = target.scrollTop;
        const scrollHeight = target.scrollHeight;
        if ((offsetHeight + scrollTop) - scrollHeight >= -100) {
            return true;
        } else {
            return false;
        }
    },
    /**
     * 判断当前tab是否需要滚动加载
     * @param {String} name 那个地方触发了滚动加载
     */

    rollingLoad(event) {
        clearTimeout(this.scrollTimer)
        this.scrollTimer=setTimeout(()=>{
          if (this.scrollLoad(event) && this.scrollLoadingFlag) {  //scrollLoadingFlag为true说明可以进行下一次请求
              this.checkedData.page += 1;      //下一次请求时，pn++
              this.loadData(this.checkedData.id, this.checkedData, this.checkedData.page)        //请求函数
          }
      },300)
    },

    loadData(parent_id = -1, data = {children: []}, pn = 0){
        this.loading=true;    //设置loading状态
        //如果pn=0,data.children的长度大于0 ，说明该级数据已经加载过，应该是树形被合上又展开的操作
        //正常加载数据时，pn==0的同时data.children==0说明第一次加载该级数据
        //pn!=0,data.children.length>0,分页加载该级数据
        if (pn === 0 && data.children.length && data.children.length > 0) {
            return;
        }
        this.scrollLoadingFlag=false;            //加载开关关闭
        let params = {
            parent_id: parent_id,
            pn: pn,
            pl: this.pl,
            type: this.type
        };
        this.$axios
            .get(
                `XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`,
                { params: params }
            )
            .then(res => {
                this.scrollLoadingFlag=true;              //加载开关打开
                this.loading=false;                              
                let { list } = res.data||[];
                // 重置滚动加载事件开关
                if (list.length < this.pl) {
                    this.scrollLoadingFlag = false;      //如果获取到的数据小于pl，数据加载完，关闭开关
                }
                //初始化右侧数据
                list.map((v, i) => {
                    if (v.subordinate_count > 1) {        //，subordinate_count 大于1说明有下一级
                        v["isLeaf"] = false;
                        v["children"] = [];
                    }
                })
                if(parent_id&&parent_id===-1){      //如果是第一级数据
                    list.map(v=>{
                        v["icons"] = "el-icon-max-zuzhijiagou-";
                    })
                    list[0]["isChecked"] = true;        //默认选中第一级数据第一个
                    this.defaultExpanded=[list[0].id];        //默认展开第一级数据第一个
                    this.checkList.push(list[0]);        //缓存点击层级顺序
                    this.checkedData=list[0];           //缓存点击层级顺序
                    this.loadData(list[0].id, list[0], list[0].page, list[0]);        //加载默认展开的下一级数据
                }
                // 判断当前节点是要添加子节点还是滚动加载
                if (this.departmentData.length === 0 && pn === 0) {      //如果树形图数据长度为0并且pn=0，说明第一次加载数据，直接赋值
                    this.departmentData = list;
                } else if (data.children && data.children.length === 0) {        //如果当前点击项children长度等于0，说明第一次加载下一级
                    this.$set(data, "children", list)
                } else {
                    data.children = data.children.concat(list)        //其他情况为分页加载，拼接数据
                }
            })
            .catch(err => {
                this.loading=false;
                this.scrollLoadingFlag=true;
                this.$message.closeAll();
                this.$message.error("请求超时");
            });
     },

     departmentNodeExpand(e, node) {
        console.log(e, '节点展开')
        this.checkedData = e;
        if (e.isLeaf && node.isLeaf||(e.children&&e.children.length>0)) return;
        this.loadData(e.id, e, e.page);
    },

    departmentNodeClick(e, node, a) {
        this.handleGray(this.checkList);        //将被点击列表取消高亮
        this.$store.dispatch("set_getRequestUser", Object.assign({}, {    //往外派发点击数据
            id:e.id,
            name:e.name
        }));
        this.checkedData = e;      //设置checkedData
        this.parent_id = e.id;
        this.checkList = [];
        this.handleBlue(node);        //将选中项高亮
   },

   handleBlue(node) {
        if (node.parent) {
            this.checkList.push(node.data);
            this.handleBlue(node.parent);
        } else {
            this.checkList.reverse();
            this.checkList.map(v => {
                v["isChecked"] = true;
            });
            this.$store.dispatch("set_getRequestUserAll",JSON.parse(JSON.stringify(this.checkList)));
            return;
        }
    },

    handleGray(arr){
        arr.map(v=>{
            v['isChecked']=false;
        })
    }


      

  }
};
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>